<?php

namespace Sharks\Core\Persistence\Pagination;

use Sharks\Core\Support\Base\Argument;
use Sharks\Core\Support\Base\Arr;
use Sharks\Core\Support\Base\DefValue;
use Sharks\Core\Support\Base\PropertiesReadOnly;

/**
 * 分页数据类
 */
class Paginator {

    use PropertiesReadOnly;
    const READ_ONLY = array(
        'totalSize', 'fetchSize', 'offset', 'size', 'hasPrev', 'hasNext', 'isLoad',
        'prevOffset', 'nextOffset', 'currentPage', 'totalPage'
    );

	/** @var  int 该项数据的总数量 */
	private $totalSize;
	/** @var int 获取的数据数量 */
	private $fetchSize;
    /** @var int 获取时的偏移量 */
	private $offset;
    /** @var int 获取时需要的数量 */
	private $size;

	/** @var bool 是否可以上翻 */
	private $hasPrev;
	/** @var bool 是否可以下翻 */
	private $hasNext;

	/** @var bool 是否有数据载入 */
	private $isLoad;

    private $prevOffset;
    private $nextOffset;
    private $currentPage;
    private $totalPage;

	public function __construct($totalSize, $data, $size = 20, $offset = 0) {
		$this->totalSize = $totalSize;
		$this->offset = $offset;
		$this->size = $size;
		$this->data = is_null($data) ? array() : $data;
		$this->fetchSize = count($this->data);
		$this->isLoad = empty($this->data) ? false : true;

		$this->hasPrev = $this->isLoad ? $this->offset > 0 : false;
		$this->hasNext = $this->isLoad ? $this->offset + $this->size < $this->totalSize : false;

        $this->prevOffset = $this->isLoad ? ($this->offset - $this->size < 0 ? 0 :intval($this->offset - $this->size)) : 0;
        $this->nextOffset = $this->isLoad ? intval($this->offset + $this->size) : 0;

        $this->currentPage = $this->isLoad ? intval($this->offset / $this->size) + 1 : 0;
        $this->totalPage = $this->isLoad ? intval($this->totalSize / $this->size) + 1 : 0;

	}

	public function hasPrev() {
		return $this->hasPrev;
	}

	public function prevOffset() {
		return $this->prevOffset;
	}

	public function nextOffset() {
		return $this->nextOffset;
	}

	public function hasNext() {
		return $this->hasNext; 
	}

	public function size() {
		return $this->size;
	}

	public function currentPage() {
		return $this->currentPage;
	}

	public function totalPage() {
		return $this->totalPage;
	}

	public function & data() {
		return $this->data;
	}

	public function isLoad() {
		return $this->isLoad;
	}

	public function totalSize() {
		return $this->totalSize;
	}

}